from django.shortcuts import render, redirect
from app02 import models
from app02.utils.form import PrettyModelForm, PrettyEditModelForm


def pretty_list(request):
    """ 靓号列表 """

    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data

    page_size = 10
    page = int(request.GET.get('page', 1))
    start = (page-1) * page_size
    end = page * page_size

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]

    return render(request, "pretty_list.html", {"queryset": queryset, "search_data": search_data})


def pretty_add(request):
    """ 添加靓号 """
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, "pretty_add.html", {"form": form})
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, "pretty_add.html", {"form": form})


def pretty_edit(request, nid):
    """ 编辑靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyEditModelForm(instance=row_object)
        return render(request, "pretty_edit.html", {"form": form})

    form = PrettyModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, "pretty_edit.html", {"form": form})


def pretty_delete(request, nid):
    """ 删除靓号 """
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")